
/*进程2——接收进程1信号、写时间字符串到文件*/
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <signal.h>
#include <time.h>

char buf[BUFSIZ] = "hello,world";

void sigusr1_handler(int signum)
{
	printf("进程2接收到SIGUSR1信号\n");

	/*打开日志文件*/
	FILE* pf = NULL;
	pf = fopen("log.txt","a");//追加写模式打开log.txt
	if(pf == NULL)
	{
		perror("fopen");
		return;
	}
	
	/*时间字符串*/
	time_t tm;
	struct tm* ptm;
	time(&tm);
	ptm = localtime(&tm);
	snprintf(buf,100,"%d-%d-%d %d:%d:%d\n", ptm->tm_year+1900, ptm->tm_mon+1,
		ptm->tm_mday, ptm->tm_hour, ptm->tm_min, ptm->tm_sec);
	printf("%s",buf);

	/*追加写入时间字符串*/
	fputs(buf, pf);

	/*关闭日志文件*/
	fclose(pf);
}

int main(int argc,char** argv)
{
	int fd;
	int pid2 = (int)getpid();

	/*捕捉SIGUSR1信号*/
	signal(SIGUSR1,sigusr1_handler);

	/*向进程1发送PID*/
	/*检查参数*/
	if(argc != 2)
	{
		printf("如要写入管道，则输入：%s 管道名\n",argv[0]);
		return 1;
	}

	/*打开管道*/
	fd = open(argv[1],O_WRONLY);
	if(fd == -1)
	{
		perror("open");
		return 1;
	}

	write(fd,&pid2,sizeof(int));//向管道写入本进程PID
	close(fd);//关闭管道

	sleep(5);
	remove(argv[1]);//删除管道

	while(1)
	{
		printf("等待SIGUSR1信号……\n");
		sleep(1);
	}

	return 0;
}
